import { BASE_URL } from '@/config';

interface ApiResponse<T = any> {
	code : number;
	msg : string;
	data ?: T;
}

interface RequestOptions<T = any> {
	url : string;
	method : string;
	data ?: T;
	ticket ?: number;
	headers ?: Record<string, string>;
}

const headers : Record<string, string> = {
	'Content-Type': 'application/json',
};

const http = {
	globalRequest: async <T>({ url, method, data, ticket = 0, headers = {} } : RequestOptions<T>) : Promise<ApiResponse<T>> => {
		const token = uni.getStorageSync('token');
		switch (ticket) {
			case 1:
				headers['satoken'] = token; //token丢入请求头
				break;
			default:
				break;
		}
		try {
			const response = await uni.request({
				timeout: 10000, // 设置超时时间为30秒
				url: `${BASE_URL}/pad${url}`,
				method,
				data,
				dataType: 'json',
				header: Object.assign({}, headers),
				xhrFields: { withCredentials: false },
				crossDomain: false,
			});
			const resData = response.data as ApiResponse<T>;
			if (resData.code !== 2000) {
				switch (resData.code) {
					case 401:
						uni.clearStorageSync();
						break;
					default:
						if (uni.getStorageSync('token')) {
							uni.showToast({
								title: resData.msg,
								icon: 'none',
							});
						}
						break;
				}
				return Promise.reject(resData);
			}
			return resData;
		} catch (error) {
			if(error.msg){
				uni.showToast({
					title: error.msg,
					icon: 'none',
				});
			}
			return Promise.reject(error);
		}
	},
};

export default http;